package cn.itcast.sailing.socket;

import cn.itcast.sailing.wyy.api.MusicApi;
import cn.itcast.sailing.wyy.domain.entity.MusicUser;
import cn.itcast.sailing.wyy.util.ExceptionConstants;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
@Slf4j
@Component
public class SailingWebSocketHandler extends TextWebSocketHandler {

    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    @Autowired
    private MusicApi api;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        // 可以在此处发送欢迎消息或其他初始化操作
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);

        // 处理接收到的消息并响应客户端
        for (WebSocketSession webSocketSession : sessions) {
            if (webSocketSession.isOpen()) {
                MusicUser user = new MusicUser();
                user.setCookie(payload);
                user.setName("weizhi..");

                Assert.notNull(user, ExceptionConstants.ACCOUNTS_AVAILABLE);
               listenSongsDaily(user, session);

            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        sessions.remove(session);
        session.close(CloseStatus.SERVER_ERROR);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }

    public void listenSongsDaily(MusicUser user,WebSocketSession session) throws IOException {

        //因为每天上限是300首，但是要歌曲不重复，如果需要不重复的300首之后停止，请轮询用户等级信息接口获取听歌量后自行判断，successCount此处只能作为记录请求次数，无法确定是否成功刷歌
        int successCount = 0;
        int nowPlayCount = Integer.parseInt(api.userLevel(user.getCookie()).getJSONObject("data").getString("nowPlayCount"));
        int upperLimit = nowPlayCount + 300;
        session.sendMessage(new TextMessage("每日听歌打卡========================="));
        log.info("每日听歌打卡=========================");
        //判断是否需要重试
        //首先获取可用的代理ip池
        //获取每日推荐歌单，保证是不影响听歌口味
        JSONObject resourceJSON = api.getRecommentSongs(user.getCookie());
        //解析歌单，返回一个map，key是歌单id,value是歌单中歌曲id的集合
        Map<Long, List<Long>> playListMap = api.parsePlayList(resourceJSON, user.getCookie());
        Set<Long> playListKeySet = playListMap.keySet();
        a:
        for (Long sourceId : playListKeySet) {
            List<Long> songIdList = playListMap.get(sourceId);
            for (Long songId : songIdList) {
                try {
                    JSONObject listenResult = api.listenSong(user.getCookie(), String.valueOf(songId), String.valueOf(sourceId));
                    if (listenResult != null && listenResult.getInteger("code") == 200) {
                        successCount++;
                        session.sendMessage(new TextMessage(": 第" + successCount + "首 : " + "====>>歌单id:" + sourceId + "===>>歌曲ID : " + songId + "目标 ：" + upperLimit));
                        log.info(user.getName() + ": 第" + successCount + "首 : " + "====>>歌单id:" + sourceId + "===>>歌曲ID : " + songId + "目标 ：" + upperLimit);
                        Thread.sleep(500);
                        //每100首检测一次
                        if (successCount >= 300 && successCount % 50 == 0) {
                            int t = Integer.parseInt(api.userLevel(user.getCookie()).getJSONObject("data").getString("nowPlayCount"));
                            if (t == upperLimit | successCount > 2000) {
                                log.info("已完成每日300首听歌当前等级听歌量为：{}", t);
                                break a;
                            }
                            log.info("当前听歌量为 : {}首,未达到目标 : {}首", t, upperLimit);
                        }
                    }
                } catch (Exception e) {
                    log.info("失败");
                }
            }
        }

    }
}
